﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using Maticsoft.Common;
using QunYing.BLL;
using QunYing.Common;
using Spore.Validator;
using System.ServiceModel;

namespace Client
{
    public partial class FrmAddGoods : BasePopForm
    {
        QunYing.Common.IImageOperator opera = QunYing.Common.ClientProxyFactory.GetProxy<QunYing.Common.IImageOperator>(QunYing.Common.GlobalInfo.ServiceImageOperationGoods);
        public string OPERTYPE = "ADD";
        public QunYing.Model.GoodsInfo editModel = null;
        public DataTable editDt = null;
        private List<string> delImg = new List<string>();
        public FrmAddGoods()
        {
            InitializeComponent();
            this.NecessaryRemark(this.cbxCategory, this.txtGoodsName, this.txtUnit, this.txtOldPrice, this.cbxZone);
            this.FormValidator.SetControlValitors(cbxCategory, ValidatorDefaults.NotNull);
            this.FormValidator.SetControlValitors(txtGoodsName, ValidatorDefaults.NotNull);
            this.FormValidator.SetControlValitors(txtUnit, ValidatorDefaults.NotNull);
            this.FormValidator.SetControlValitors(txtOldPrice, ValidatorDefaults.Float);
            this.FormValidator.SetControlValitors(cbxZone, ValidatorDefaults.NotNull);
            cbxDown.SelectedIndex = 1;
            CbxBind();
        }
        protected override void OnFormClosed(FormClosedEventArgs e)
        {
            (opera as ICommunicationObject).Close();
            base.OnFormClosed(e);
        }
        private void CbxBind()
        {
            QunYing.BLL.Category category = new Category();
            DataTable dt = category.GetList( "经销商编号='"+GlobalInfo.UserLoginInfo.用户ID
                +"' AND 类别ID NOT IN (SELECT 父类别ID FROM dbo.Category where 经销商编号='"
                +GlobalInfo.UserLoginInfo.用户ID+"')").Tables[0];
            DataTable dtAll = new DataTable();
            dtAll.Columns.Add("类别ID");
            dtAll.Columns.Add("类别名称");
            foreach (DataRow dr in dt.Rows)
            {
                dtAll.Rows.Add(dr["类别ID"],dr["类别名称"]);
            }
            cbxCategory.Properties.DataSource = dtAll;
            cbxCategory.Properties.ValueMember = "类别ID";
            cbxCategory.Properties.DisplayMember = "类别名称";
            cbxCategory.ItemIndex = 0;
        }
        private void cbxZone_SelectedIndexChanged(object sender, EventArgs e)
        {
            lblMsg.Visible = true;
            if (cbxZone.Text == "热门推荐")
            {
                lblMsg.Text = "温馨提示:热门推荐将以原价出售，并赠送用户积分!";
            }
            if (cbxZone.Text == "特价专区")
            {
                lblMsg.Text = "温馨提示:特价专区将以现价出售，并赠送用户积分!";
            }
            if (cbxZone.Text == "积分兑换")
            {
                lblMsg.Text = "温馨提示:积分兑换只扣减用户积分!";
            }
        }

        private void btnNew_Click(object sender, EventArgs e)
        {
            OpenFileDialog dag = new OpenFileDialog();
            dag.Filter = "Image Files(*.JPG;*.GIF;*.PNG;*.BMP)|*.JPG;*.GIF;*PNG,*.BMP";
            if (dag.ShowDialog() == DialogResult.OK)
            {
                listImg.Items.Add(dag.FileName);
            }
        }

        private void btnDel_Click(object sender, EventArgs e)
        {
            if (listImg.SelectedIndex >= 0)
            {
                delImg.Add(listImg.SelectedValue.ToString());
                listImg.Items.RemoveAt(listImg.SelectedIndex);

            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            if (!this.FormValidator.ValidAll()) return;
            if (cbxZone.Text == "特价专区")
            {
                if (txtNewPrice.Text.Trim() == "")
                {
                    GlobalInfo.MsgBoxShowError("现价不能为空！");
                    return;
                }
               
            }
            if (cbxZone.Text == "积分兑换")
            {
                if (txtUseScore.Text.Trim() == "")
                {
                    GlobalInfo.MsgBoxShowError("兑换积分不能为空！");
                    return;
                }
            }

            if (!string.IsNullOrEmpty(txtNewPrice.Text.Trim()))
            {
                try
                {
                    Convert.ToDecimal(txtNewPrice.Text.Trim());
                }
                catch (Exception)
                {

                    GlobalInfo.MsgBoxShowError("现价格式错误！");
                    return;
                }
            }
            if (!string.IsNullOrEmpty(txtWeight.Text.Trim()))
            {
                try
                {
                    Convert.ToDecimal(txtWeight.Text.Trim());
                }
                catch (Exception)
                {
                    GlobalInfo.MsgBoxShowError("重量格式错误！");
                    return;
                }
            }
            if (!string.IsNullOrEmpty(txtUseScore.Text.Trim()))
            {
                try
                {
                    Convert.ToInt32(txtUseScore.Text.Trim());
                }
                catch (Exception)
                {
                    GlobalInfo.MsgBoxShowError("兑换积分格式错误！");
                    return;
                }
            }
            if (!string.IsNullOrEmpty(txtGetScore.Text.Trim()))
            {
                try
                {
                    Convert.ToInt32(txtGetScore.Text.Trim());
                }
                catch (Exception)
                {
                    GlobalInfo.MsgBoxShowError("赠送积分格式错误！");
                    return;
                }
            }
            QunYing.BLL.GoodsInfo goodsInfo = new GoodsInfo();
            DataSet ds = goodsInfo.GetList("经销商编号='" + GlobalInfo.UserLoginInfo.用户ID
                + "' AND 商品名称='" + txtGoodsName.Text.Trim() + "' AND 商品品牌='" + txtBrand.Text.Trim() + "'");
            if (ds.Tables[0].Rows.Count > 0)
            {
                if (OPERTYPE == "EDIT" && editModel != null)
                {
                    if (editModel.商品ID.ToString() == ds.Tables[0].Rows[0]["商品ID"].ToString())
                    {

                    }
                    else
                    {
                        GlobalInfo.MsgBoxShowError("已经存在同品牌同名称商品,请更名！");
                        return;
                    }
                }
                else
                {
                    GlobalInfo.MsgBoxShowError("已经存在同品牌同名称商品,请更名！");
                    return;
                }

            }
            AddGoods();
        }

        private void AddGoods()
        {
            QunYing.BLL.GoodsInfo goodsInfo = new GoodsInfo();

            QunYing.Model.GoodsInfo model = new QunYing.Model.GoodsInfo();
            model.经销商编号 = GlobalInfo.UserLoginInfo.用户ID;
            model.条形码 = txtCode.Text.Trim();
            model.类别ID = Convert.ToInt32(cbxCategory.EditValue.ToString());
            model.商品名称 = txtGoodsName.Text.Trim();
            model.商品描述 = txtContent.Text.Trim();
            model.商品品牌 = txtBrand.Text.Trim();
            model.重量 = txtWeight.Text.Trim() == "" ? 0M : Convert.ToDecimal(txtWeight.Text.Trim());
            model.单位 = txtUnit.Text.Trim();
            model.原价 = Convert.ToDecimal(txtOldPrice.Text.Trim());
            model.现价 = txtNewPrice.Text.Trim() == "" ? 0M : Convert.ToDecimal(txtNewPrice.Text.Trim());
            model.赠送积分 = txtGetScore.Text.Trim() == "" ? 0 : Convert.ToInt32(txtGetScore.Text.Trim());
            model.兑换积分 = txtUseScore.Text.Trim() == "" ? 0 : Convert.ToInt32(txtUseScore.Text.Trim());
            model.是否推荐 = cbxZone.Text == "热门推荐" ? true : false;
            model.是否折价 = cbxZone.Text == "特价专区" ? true : false;
            model.是否兑换 = cbxZone.Text == "积分兑换" ? true : false;
            model.添加日期 = DateTime.Now;
            model.更新日期 = DateTime.Now;
            model.是否下架 = cbxDown.SelectedIndex == 0 ? true : false;
            if (OPERTYPE == "ADD")
            {
                model.显示顺序 = 1;
                int k = goodsInfo.Add(model);
                if (k > 0)
                {
                    UploadImg(k.ToString());
                    GlobalInfo.MsgBoxShow("添加成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    FrmGoodsManager.frm.QueryData();
                    this.Close();
                }
                else
                {
                    GlobalInfo.MsgBoxShowError("添加失败!");
                }
            }
            else if (OPERTYPE == "EDIT")
            {
                model.显示顺序 = editModel.显示顺序;
                model.商品ID = editModel.商品ID;
                bool b = goodsInfo.Update(model);
                if (b)
                {
                    EditImg(editModel.商品ID.ToString());
                    GlobalInfo.MsgBoxShow("修改成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    FrmGoodsManager.frm.QueryData();
                    this.Close();
                }
                else
                {
                    GlobalInfo.MsgBoxShowError("修改失败!");
                }
            }
        }

        private bool UploadImg(string m)
        {
            List<string> listPath = new List<string>();
            List<Bitmap> listImgs = new List<Bitmap>();
            for (int i = 0; i < this.listImg.Items.Count; i++)
            {
                if (!listImg.Items[i].ToString().StartsWith(QunYing.Common.GlobalInfo.ImageRelativePath))
                {
                    Bitmap image = (Bitmap)Bitmap.FromFile(listImg.Items[i].ToString());
                    string strPath = GetImagePath(listImg.Items[i].ToString(), m, DateTime.Now.ToString("yyMMddHHmmssfff") + i);
                    listPath.Add(strPath);
                    listImgs.Add(image);

                    QunYing.Model.GoodsImg model = new QunYing.Model.GoodsImg();
                    model.商品ID = Convert.ToInt16(m);
                    model.图片路径 = QunYing.Common.GlobalInfo.ImageRelativePath + strPath;
                    model.默认图片 = i == 0 ? true : false;
                    QunYing.BLL.GoodsImg goodsImg = new GoodsImg();
                    goodsImg.Add(model);

                }
            }
            try
            {
                opera.UpLoad("", listPath.ToArray(), listImgs.ToArray());
            }
            catch (Exception ex)
            {
                QunYing.Common.Loger.Log.Error("上传图片时发生错误:" + ex.Message);
            }
            return true;
        }


        private bool EditImg(string m)
        {
            try
            {
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < delImg.Count; i++)
                {
                    sb.Append("'" + delImg[i].ToString() + "',");
                }
                if (sb.Length > 0)
                {
                    QunYing.BLL.GoodsImg goodsImg = new GoodsImg();
                    bool b = goodsImg.DeleteList(m, sb.ToString().Remove(sb.ToString().Length - 1));
                    if (b)
                    {
                        opera.DeleteImg(delImg.ToArray());
                    }
                }

                UploadImg(m);
            }
            catch (Exception ex)
            {
                QunYing.Common.Loger.Log.Error("上传图片时发生错误:" + ex.Message);
            }
            return true;
        }


        private string GetImagePath(string path, string m, string n)
        {
            string strType = path.Substring(path.LastIndexOf('.'));
            DataTable dt = new QunYing.BLL.Category().GetParentCategory(cbxCategory.EditValue.ToString());
            StringBuilder sb = new StringBuilder();
            sb.Append(@"Goods\" + GlobalInfo.UserLoginInfo.用户ID + @"\");
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                sb.Append(dt.Rows[0]["类别名称"] + @"\");
            }
            sb.Append(m + @"\" + n + strType);
            return sb.ToString();
        }

        private void listImg_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (listImg.SelectedValue != null)
                {
                    if (listImg.SelectedValue.ToString().StartsWith(QunYing.Common.GlobalInfo.ImageRelativePath))
                    {
                        Bitmap[] bp = opera.GetImgs(new string[] { listImg.SelectedValue.ToString() });
                        if (bp.Length != 0)
                        {
                            this.pictureEdit1.Image = bp[0];
                        }
                        else
                        {
                            this.pictureEdit1.Image = null;
                        }
                    }
                    else
                    {
                        pictureEdit1.Image = System.Drawing.Image.FromFile(listImg.SelectedValue.ToString());
                    }

                }
            }
            catch (Exception)
            {
                this.pictureEdit1.Image = null;
            }


        }

        private void FrmAddGoods_Load(object sender, EventArgs e)
        {
            if (OPERTYPE == "EDIT" && editModel != null)
            {
                BindInfo(editModel, editDt);
            }
        }

        private void BindInfo(QunYing.Model.GoodsInfo model, DataTable dt)
        {
            cbxCategory.EditValue = model.类别ID.ToString();
            txtCode.Text = model.条形码;
            txtBrand.Text = model.商品品牌;
            txtContent.Text = model.商品描述;
            txtGetScore.Text = model.赠送积分.ToString();
            txtGoodsName.Text = model.商品名称;
            txtNewPrice.Text = model.现价.ToString();
            txtOldPrice.Text = model.原价.ToString();
            txtUnit.Text = model.单位;
            txtUseScore.Text = model.兑换积分.ToString();
            txtWeight.Text = model.重量.ToString();
            if (model.是否推荐)
            {
                cbxZone.SelectedIndex = 0;
            }
            if (model.是否折价)
            {
                cbxZone.SelectedIndex = 1;
            }
            if (model.是否兑换)
            {
                cbxZone.SelectedIndex = 2;
            }
            cbxDown.SelectedIndex = model.是否下架 ? 0 : 1;

            foreach (DataRow dr in dt.Rows)
            {
                listImg.Items.Add(dr["图片路径"].ToString());
            }
        }
    }
}